package server.xml;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.Servlet;
import server.StaticResourceUtil;
import server.container.*;
import server.loader.WebappClassLoader;
import urls.UrlUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * dom4j解析Server.xml配置文件
 * 并解析Server中配置的Webapps下的发布工程的web.xml的配置文件
 */
public class LoadServer {

    /**
     * 解析server.xml配置文件，并返回配置的多个Service
     * @return
     */
    public List<Service> parseServerXML(){
        InputStream resourceAsStream = null;
        SAXReader saxReader = null;
        List<Service> serviceList = null;
        try {
            resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
            saxReader = new SAXReader();
            Document document = null;
            document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            serviceList = parseServers(rootElement);
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        }

        return serviceList;

    }

    /**
     * 解析Server节点，一个Server对应多个service
     * @param rootElement
     * @return
     * @throws FileNotFoundException
     */
    private List<Service> parseServers(Element rootElement) throws FileNotFoundException {
        List<Element> selectNodes = rootElement.selectNodes("//Service");
        List<Service> serviceList =  new ArrayList<>();
        for(Element ele:selectNodes){
            serviceList.add(parseService(ele));
        }
        return serviceList;
    }

    /**
     * 解析service节点
     * @param serviceEle
     * @return
     * @throws FileNotFoundException
     */
    private Service parseService(Element serviceEle) throws FileNotFoundException {
        Service service = new Service();
        Connector connector = new Connector();
        // 解析Connector节点
        Element connEle = serviceEle.element("Connector");
        // 获得配置的port
        String portStr = connEle.attributeValue("port");
        connector.setPort(Integer.parseInt(portStr));
        service.setConnector(connector);
        // 解析Engine节点
        Engine engine = new Engine();
        Element engineEle = serviceEle.element("Engine");
        // 解析host节点
        engine.setHostMap(parseHost(engineEle.selectNodes("//Host")));
        service.setEngine(engine);
        return service;
    }

    /**
     * 解析host节点
     * @param hostElements
     * @return
     * @throws FileNotFoundException
     */
    private Map<String,Host> parseHost(List<Element> hostElements) throws FileNotFoundException {
        Map<String,Host> hostMap = new HashMap<>();
        Host host = null;
        for (Element hostElement : hostElements) {
            host = new Host();
            // 获得name
            host.setName(hostElement.attributeValue("name"));
            // 获得webapps路径
            host.setAppBase(hostElement.attributeValue("appBase"));
            host.setContextMap(parseWebapps(new File(host.getAppBase())));
            hostMap.put(host.getName().trim(),host);
        }
        return hostMap;
    }

    /**
     * 解析webapps下的部署工程
     * @param file
     * @return
     * @throws FileNotFoundException
     */
    private Map<String,Context> parseWebapps(File file) throws FileNotFoundException {
        Map<String,Context> contextMap = new HashMap<>();
        if(!file.exists()){
            return contextMap;
        }
        File[] subFiles = file.listFiles();
        if(null ==subFiles || subFiles.length<=0){
            return contextMap;
        }

        Context context = null;
        for(File sFile:subFiles){
            context = new Context();
            context.setWrapperMap(loadServlet(sFile.getPath()));
            context.setName(sFile.getName());
            contextMap.put(sFile.getName().trim(),context);
        }
        return contextMap;
    }

    /**
     * 解析web.xml
     * @param basePath
     * @return
     * @throws FileNotFoundException
     */
    private  Map<String, Wrapper> loadServlet(String basePath) throws FileNotFoundException {
        InputStream resourceAsStream = new FileInputStream(UrlUtils.joinUrl(basePath,"/web.xml"));
        SAXReader saxReader = new SAXReader();
        Wrapper  wrapper =  null;
        Map<String, Wrapper> servletMap = new HashMap<>();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            // 实例化自定义ClassLoader
            WebappClassLoader classLoader = new WebappClassLoader(this.getClass().getClassLoader());
            // 设置自定义classpath
            classLoader.loadClassPath(basePath);
//            classLoader.loadClassPath(UrlUtils.joinUrl(basePath,"WEB-INF/classes"));
//            classLoader.loadJarPath(UrlUtils.joinUrl(basePath,"WEB-INF/lib"));
            // 加载url
            classLoader.loadUrls();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                wrapper = new Wrapper();
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                // 获得Servlet实例
                wrapper.setServlet((Servlet) classLoader.loadClass(servletClass).newInstance());
                wrapper.setServletName(servletName);
                wrapper.setServletClass(servletClass);
                wrapper.setUrlPatten(urlPattern);
                servletMap.put(urlPattern.trim(),wrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return servletMap;
    }


}
